﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web;
using System.Net;
using yq.ControllerBase;
using yq.ControllerBase.CaChe;
using System.ComponentModel.DataAnnotations;

namespace yq.ControllerBase
{
    /// <summary>
    /// 控制器基类 （需要继承）
    /// </summary>
    public  class BaseController : Controller
    {
        /// <summary>
        /// 找不到方法时404处理
        /// </summary>
        /// <param name="actionName"></param>
        protected override void HandleUnknownAction(string actionName)
        {
            ErrorFilterAttribute.GetError404(this.Server, this, this.Response);
        }

        /// <summary>
        /// 获取当前用户
        /// </summary>
        /// <returns></returns>
        public static CurrentUser GetCurrentUser
        {
            get
            {
                return new CurrentUser();
            }
        }

        /// <summary>
        /// 权限处理类
        /// </summary>
        /// <param name="filterContext"></param>
        public virtual void Purview(ActionExecutingContext filterContext)
        {
            
        }

        /// <summary>
        /// 获取文本信息
        /// </summary>
        /// <param name="fileid"></param>
        /// <returns></returns>
        public virtual string DownFileTxt(string fileid)
        {
            throw new Exception("未重写该方法");
        }

        /// <summary>
        /// 异常写入
        /// </summary>
        /// <param name="errorText"></param>
        /// <param name="exception"></param>
        public virtual void LogWriteAsyn(string errorText, string exception)
        {
            //throw new Exception("未重写该方法");
        }

        /// <summary>
        /// 重写方法，在运行Action方法前调用
        /// 权限判断
        /// </summary>
        /// <param name="filterContext">上下文信息</param>
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (IsExistAttribute<NoPurviewFilterAttribute>(filterContext.ActionDescriptor)==false)
            {
                Purview(filterContext);
            }
        }

        /// <summary>
        /// 获取VerifyFilter中使用过的对象
        /// </summary>
        /// <returns></returns>
        public virtual T GetModel<T>() where T :  class, new()
        {
            ViewDataDictionary ViewData=this.ViewData;
            var info= ViewData[VerifyFilterAttribute.KeyString] as T;

            return info;
        }

        /// <summary>
        /// 方法内是否包含这个特性
        /// IsExistAttribute<NoPurviewFilterAttribute>(filterContext.ActionDescriptor)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="action"></param>
        /// <returns></returns>
        public bool IsExistAttribute<T>(ActionDescriptor action) where T : class
        {
            //获取权限数据
            object[] attributes = action.GetCustomAttributes(typeof(T), true);
            if (attributes != null && attributes.Length > 0)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// TryUpdateModel 只验证Request.Form传入的数据
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <param name="model">更新的对象</param>
        /// <param name="requestForm">页面 this.Request.Form 集合</param>
        /// <param name="prefix">前缀名</param>
        /// <returns></returns>
        public bool TryUpdateModel<TModel>(
            TModel model,
            System.Collections.Specialized.NameValueCollection requestForm,
            string prefix = null) where TModel : class
        {
            bool outbool = true;
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            IValueProvider valueProvider = ValueProviderFactories.Factories.GetValueProvider(ControllerContext);

            Predicate<string> propertyFilter = propertyName => true;
            IModelBinder binder = Binders.GetBinder(typeof(TModel));

            ModelBindingContext bindingContext = new ModelBindingContext()
            {
                ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, typeof(TModel)),
                ModelName = prefix,
                ModelState = ModelState,
                PropertyFilter = propertyFilter,
                ValueProvider = valueProvider
            };
            binder.BindModel(ControllerContext, bindingContext);

            var metadataTypeAttribute = (MetadataTypeAttribute)bindingContext.ModelMetadata.ModelType.GetCustomAttributes(typeof(MetadataTypeAttribute), false)[0];
            foreach (string key in ModelState.Keys)
            {
                //如果有错误 并且在form中也有这个数据
                if (ModelState[key].Errors.Count > 0 && requestForm[key] != null)
                {
                    outbool = false;
                    break;
                }
            }
            return outbool;
        }
    }
}
